/**
 * 宝宝信息管理API路由
 */
import express, { type Request, type Response } from 'express';

const router = express.Router();

// 宝宝信息接口类型定义
interface Baby {
  id: string;
  name: string;
  avatar: string;
  gender: 'male' | 'female';
  birthday: string;
  age: {
    years: number;
    months: number;
    days: number;
  };
  height?: number;
  weight?: number;
  bloodType?: string;
  allergies?: string[];
  vaccinations?: {
    name: string;
    date: string;
    nextDate?: string;
  }[];
  milestones?: {
    type: string;
    description: string;
    date: string;
    achieved: boolean;
  }[];
  createdAt: string;
  updatedAt: string;
}

// 模拟数据存储
let babies: Baby[] = [
  {
    id: '1',
    name: '小宝',
    avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=cute%20baby%20avatar%20cartoon%20style&image_size=square',
    gender: 'male',
    birthday: '2023-06-15',
    age: {
      years: 1,
      months: 6,
      days: 10
    },
    height: 75,
    weight: 9.5,
    bloodType: 'O',
    allergies: ['牛奶', '鸡蛋'],
    vaccinations: [
      {
        name: 'BCG疫苗',
        date: '2023-06-16',
        nextDate: '2024-06-16'
      },
      {
        name: '乙肝疫苗',
        date: '2023-07-15'
      }
    ],
    milestones: [
      {
        type: '运动发育',
        description: '会坐',
        date: '2023-12-15',
        achieved: true
      },
      {
        type: '语言发育',
        description: '会叫爸爸妈妈',
        date: '2024-01-10',
        achieved: true
      }
    ],
    createdAt: '2023-06-15T08:00:00Z',
    updatedAt: '2024-01-15T10:30:00Z'
  }
];

/**
 * 获取宝宝列表
 * GET /api/baby/list
 */
router.get('/list', (req: Request, res: Response) => {
  try {
    const { page = 1, pageSize = 10 } = req.query;
    const startIndex = (Number(page) - 1) * Number(pageSize);
    const endIndex = startIndex + Number(pageSize);
    
    const paginatedBabies = babies.slice(startIndex, endIndex);
    
    res.json({
      success: true,
      data: {
        list: paginatedBabies,
        total: babies.length,
        page: Number(page),
        pageSize: Number(pageSize),
        hasMore: endIndex < babies.length
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '获取宝宝列表失败'
    });
  }
});

/**
 * 获取宝宝详情
 * GET /api/baby/:id
 */
router.get('/:id', (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const baby = babies.find(b => b.id === id);
    
    if (!baby) {
      return res.status(404).json({
        success: false,
        error: '宝宝信息不存在'
      });
    }
    
    res.json({
      success: true,
      data: baby
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '获取宝宝详情失败'
    });
  }
});

/**
 * 创建宝宝信息
 * POST /api/baby
 */
router.post('/', (req: Request, res: Response) => {
  try {
    const { name, gender, birthday, avatar, height, weight, bloodType, allergies } = req.body;
    
    if (!name || !gender || !birthday) {
      return res.status(400).json({
        success: false,
        error: '姓名、性别和生日为必填项'
      });
    }
    
    // 计算年龄
    const birthDate = new Date(birthday);
    const now = new Date();
    const ageInMs = now.getTime() - birthDate.getTime();
    const ageInDays = Math.floor(ageInMs / (1000 * 60 * 60 * 24));
    const years = Math.floor(ageInDays / 365);
    const months = Math.floor((ageInDays % 365) / 30);
    const days = ageInDays % 30;
    
    const newBaby: Baby = {
      id: Date.now().toString(),
      name,
      avatar: avatar || `https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=cute%20${gender}%20baby%20avatar%20cartoon%20style&image_size=square`,
      gender,
      birthday,
      age: { years, months, days },
      height,
      weight,
      bloodType,
      allergies: allergies || [],
      vaccinations: [],
      milestones: [],
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    };
    
    babies.push(newBaby);
    
    res.status(201).json({
      success: true,
      data: newBaby
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '创建宝宝信息失败'
    });
  }
});

/**
 * 更新宝宝信息
 * PUT /api/baby/:id
 */
router.put('/:id', (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const babyIndex = babies.findIndex(b => b.id === id);
    
    if (babyIndex === -1) {
      return res.status(404).json({
        success: false,
        error: '宝宝信息不存在'
      });
    }
    
    const updatedBaby = {
      ...babies[babyIndex],
      ...req.body,
      id, // 确保ID不被修改
      updatedAt: new Date().toISOString()
    };
    
    // 重新计算年龄
    if (req.body.birthday) {
      const birthDate = new Date(req.body.birthday);
      const now = new Date();
      const ageInMs = now.getTime() - birthDate.getTime();
      const ageInDays = Math.floor(ageInMs / (1000 * 60 * 60 * 24));
      const years = Math.floor(ageInDays / 365);
      const months = Math.floor((ageInDays % 365) / 30);
      const days = ageInDays % 30;
      updatedBaby.age = { years, months, days };
    }
    
    babies[babyIndex] = updatedBaby;
    
    res.json({
      success: true,
      data: updatedBaby
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '更新宝宝信息失败'
    });
  }
});

/**
 * 删除宝宝信息
 * DELETE /api/baby/:id
 */
router.delete('/:id', (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const babyIndex = babies.findIndex(b => b.id === id);
    
    if (babyIndex === -1) {
      return res.status(404).json({
        success: false,
        error: '宝宝信息不存在'
      });
    }
    
    babies.splice(babyIndex, 1);
    
    res.json({
      success: true,
      message: '删除成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '删除宝宝信息失败'
    });
  }
});

/**
 * 添加疫苗接种记录
 * POST /api/baby/:id/vaccination
 */
router.post('/:id/vaccination', (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { name, date, nextDate } = req.body;
    
    const babyIndex = babies.findIndex(b => b.id === id);
    if (babyIndex === -1) {
      return res.status(404).json({
        success: false,
        error: '宝宝信息不存在'
      });
    }
    
    if (!name || !date) {
      return res.status(400).json({
        success: false,
        error: '疫苗名称和接种日期为必填项'
      });
    }
    
    const vaccination = { name, date, nextDate };
    babies[babyIndex].vaccinations = babies[babyIndex].vaccinations || [];
    babies[babyIndex].vaccinations!.push(vaccination);
    babies[babyIndex].updatedAt = new Date().toISOString();
    
    res.json({
      success: true,
      data: vaccination
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '添加疫苗记录失败'
    });
  }
});

/**
 * 添加发育里程碑
 * POST /api/baby/:id/milestone
 */
router.post('/:id/milestone', (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { type, description, date, achieved = false } = req.body;
    
    const babyIndex = babies.findIndex(b => b.id === id);
    if (babyIndex === -1) {
      return res.status(404).json({
        success: false,
        error: '宝宝信息不存在'
      });
    }
    
    if (!type || !description || !date) {
      return res.status(400).json({
        success: false,
        error: '类型、描述和日期为必填项'
      });
    }
    
    const milestone = { type, description, date, achieved };
    babies[babyIndex].milestones = babies[babyIndex].milestones || [];
    babies[babyIndex].milestones!.push(milestone);
    babies[babyIndex].updatedAt = new Date().toISOString();
    
    res.json({
      success: true,
      data: milestone
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '添加里程碑失败'
    });
  }
});

export default router;